####### Target #######
TARGET = $(wildcard *.tex)

ARCHIVE_DIR = archive
EXPERIMENTS_DIR = experiments
SKIP_ZIP_DIRS = 
PROJECT_NAME = $(notdir $(CURDIR))

####### Options #######
# Default target
DEFAULT = ps
# If set to "yes", the eps images will be removed on "make clean" if there is a fig file with the same name
CLEARFIGIMGS = yes
CLEARPDFIMGS = yes

###### Commands ######
LATEX = latex
BIBTEX = bibtex
DVIPS = dvips
PDFLATEX = pdflatex
RTFLATEX = latex2rtf
INDEX = index
FIG2EPS = fig2dev -L eps
GFTOPK = gftopk
PS2PDF = ps2pdf
EPS2PDF = epstopdf --embed
MF = mf
SHELL = /bin/bash -O extglob -O nullglob
###### End of commands ######

# Per dir override file
-include Makefile.overrides
-include Makefile.override

# Defaut rule
default: $(DEFAULT)

DVI_TARGET=$(patsubst %.tex, %.dvi, $(TARGET))
PS_TARGET=$(patsubst %.tex, %.ps, $(TARGET))
PDF_TARGET=$(patsubst %.tex, %.pdf, $(TARGET))
RTF_TARGET=$(patsubst %.tex, %.rtf, $(TARGET))

# Main rules
ps: $(PS_TARGET)
dvi: $(DVI_TARGET)
pdf: $(PDF_TARGET)
rtf: $(RTF_TARGET)

all: ps pdf rtf

###### Build rules ######

AUXCMD=$(LATEX)
AUXEXT=eps
ifeq "$(DEFAULT)" "pdf"
AUXCMD=$(PDFLATEX)
AUXEXT=pdf
CLEARPDFIMGS=no
PS2PDF=
endif

%.aux: %.tex
	@$(AUXCMD) $<

ifneq "$(PS2PDF)" ""
%.pdf: %.ps
	@$(PS2PDF) $<
else
%.pdf: %.tex
	@$(PDFLATEX) $<
	@$(PDFLATEX) $<
endif

%.dvi: %.tex
	@$(LATEX) $<
	@$(LATEX) $<

%.ps: %.dvi
	@$(DVIPS) $< -o $@

%.bbl: %.aux
	@$(BIBTEX) $*

%.idl: %.idx
	@$(INDEX) -z il2 $*.idx

%.idx: %.tex
	@$(LATEX) $<

%.600pk: %.mf
	@$(MF) "\mode=ljfour; input $<"
	@$(GFTOPK) $*.600gf
	@rm -f $*.600gf

%.eps: %.fig
	@$(FIG2EPS) $< > $@
	
%.pdf: %.eps
	@$(EPS2PDF) $< > $@

%.rtf: %.tex %.aux
	$(RTFLATEX) $<

###### Special targets ######

clean: tmp-clean eps-fig-clean
	@rm -f $(DVI_TARGET) $(PDF_TARGET) $(RTF_TARGET) $(PS_TARGET) $(PROJECT_NAME).zip
tmp-clean: pdf-fig-clean
	@rm -f *.aux *.log *.out *.toc *.600gf *.600pk *.tfm *.blg *.bbl *.idx *.ind *.inx *.ilg .depend
pdf-fig-clean:
ifeq "$(CLEARPDFIMGS)" "yes"
	@find -name '*.eps' | while read file;do rm -f $${file%.eps}.pdf;done
endif
eps-fig-clean:
ifeq "$(CLEARFIGIMGS)" "yes"
	@find -name '*.fig' | while read file;do rm -f $${file%.fig}.eps;done
endif

archive: clean
	@mkdir -p "$(ARCHIVE_DIR)"
	@tar -zhcf "$(ARCHIVE_DIR)/$(PROJECT_NAME)-`date +%y%m%d`.tgz" !($(ARCHIVE_DIR)) .[!.]*

zip: pdf
	@rm -f $(PROJECT_NAME).zip
	@zip -r $(PROJECT_NAME).zip !($(ARCHIVE_DIR)|$(EXPERIMENTS_DIR)|$(SKIP_ZIP_DIRS)|Makefile*)

DEPENDSCRIPT='\
		my %targets;\
		my %parfiles;\
		my @imagefiles;\
		sub parse_cmd {\
			my $$cmd = shift;\
			\
			if ($$cmd eq "epsfig") {\
				@_ = grep {/file=(.*)/ && ($$_ = $$1)} @_;\
				push(@imagefiles, @_);\
			} elsif ($$cmd eq "includeepspdf" || $$cmd eq "epspdffig" || $$cmd eq "includeeps" || $$cmd eq "includegraphics" || $$cmd eq "epsffile") {\
				push(@imagefiles, @_);\
			} elsif ($$cmd eq "bibliography") {\
				@_ = map {"$$_.bib"} @_;\
			} elsif ($$cmd eq "input") {\
				unshift(@ARGV, @_);\
				map { $$parfiles{$$_} = $$ARGV } @_;\
			} elsif ($$cmd eq "include") {\
				@_ = map {"$$_.tex"} @_;\
				unshift(@ARGV, @_);\
				map { $$parfiles{$$_} = $$ARGV } @_;\
			} else {\
				return;\
			}\
			push(@{$$targets{substr($$parfiles{$$ARGV} || $$ARGV, 0, -4)}}, @_);\
		}\
		sub checkfile {\
			$$_ = shift;\
			return $$_ if (/\..{3}$$/ || -r $$_);\
			foreach my $$ext (@_) {\
				return "$$_.$$ext" if (-r "$$_.$$ext");\
			}\
			return "$$_." . @_[0];\
		}\
		while ($$ARGV = shift(@ARGV)) {\
			open(FILE, $$ARGV) || die "Cannot open $$ARGV: $$!";\
			while(<FILE>) {\
				s/\%.*$$//g;\
				parse_cmd(lc($$1), split(/\s*,\s*/, $$3)) if (/([a-z]+)(\[.+?\])*{\s*([^\#}]+?)\s*}/i);\
				last if /\\end\{document\}/;\
			}\
			close(FILE);\
		}\
		print "images: ", join(" ", map { checkfile($$_, "$(AUXEXT)", "jpg", "png") } @imagefiles), "\n";\
		foreach my $$target (keys %targets) {\
			print $$target, ".aux: ", join(" ", map { checkfile($$_, "$(AUXEXT)", "jpg", "png") } @{$$targets{$$target}}), "\n";\
			my @bibtex = grep(/\.bib$$/, @{$$targets{$$target}});\
			if (@bibtex) {\
				print $$target, ".bbl: ", join(" ", @bibtex), "\n";\
				push(@{$$targets{$$target}}, $$target.".bbl");\
			}\
			print $$target, ".dvi: ", join(" ", map { checkfile($$_, "eps") } @{$$targets{$$target}}), "\n";\
			print $$target, ".rtf: ", join(" ", map { checkfile($$_, "eps") } @{$$targets{$$target}}), "\n";\
			print $$target, ".pdf: ", join(" ", map { checkfile($$_, "pdf", "jpg", "png") } @{$$targets{$$target}}), "\n";\
		}'
.depend: $(TARGET) /usr/bin/perl
	@/usr/bin/perl -e $(DEPENDSCRIPT) $(TARGET) > .depend
sinclude .depend
